package top.mcwebsite.playandroid.business.tixi.impl.vm

import ArticleListIntent
import ArticleListUiEffect
import ArticleListUiState
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingSource
import androidx.paging.PagingState
import top.mcwebsite.playandroid.business.articles.api.model.ArticleModel
import top.mcwebsite.playandroid.business.tixi.impl.api.TixiApiService
import top.mcwebsite.playandroid.common.network.api.NetworkService
import top.mcwebsite.playandroid.common.network.api.createApi
import top.mcwebsite.playandroid.common.network.model.ApiResult
import top.mcwebsite.playandroid.lib.mvi.base.BaseViewModel
import top.mcwebsite.playandroid.lib.servicemanager.core.ServiceManager

class ArticleListViewModel :
    BaseViewModel<ArticleListIntent, ArticleListUiState, ArticleListUiEffect>(ArticleListUiState()) {

    private val apiService: TixiApiService = ServiceManager.getService<NetworkService>()
        .createApi()

    private val pager = Pager(PagingConfig(pageSize = 10)) {
        ArticleListPagingSource()
    }

    val pagerFlow = pager.flow

    var cid: Long = -1L

    override fun handleIntent(intent: ArticleListIntent) {
        when (intent) {
            is ArticleListIntent.GoArticleDetailPageIntent -> {
                sendUiEffect(ArticleListUiEffect.GoArticleDetailPageUiEffect(intent.articleModel))
            }
        }
    }

    private inner class ArticleListPagingSource : PagingSource<Int, ArticleModel>() {
        override fun getRefreshKey(state: PagingState<Int, ArticleModel>): Int? {
            return null
        }

        override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ArticleModel> {
            check(cid != -1L) {
                "cid 没有初始化"
            }
            return try {
                val nextPageNumber = params.key ?: 0
                when (val result = apiService.articleList(nextPageNumber, cid)) {
                    is ApiResult.Success -> {
                        LoadResult.Page(
                            data = result.data.data?.datas ?: emptyList(),
                            prevKey = if (nextPageNumber == 0) null else nextPageNumber - 1,
                            nextKey = if (result.data.data?.over == true) null else nextPageNumber + 1
                        )
                    }

                    is ApiResult.Failure -> {
                        LoadResult.Error(result.cause)
                    }
                }
            } catch (e: Exception) {
                return LoadResult.Error(e)
            }
        }

    }
}